package com.cloud.quickconfigure.web;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * web请求统一拦截器
 *
 * @author NiJo_H
 * @version 1.0
 * @date 2019/8/22 22:00
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 跨域支持
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "HEAD", "OPTIONS",
                "DELETE");
    }

    /**
     * 添加类型转换器和格式化器
     *
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(String.class, LocalDate.class, s -> {
            if (StringUtils.hasText(s)) {
                return LocalDate.parse(s);
            }
            return null;
        });
        registry.addConverter(String.class, LocalDateTime.class, s -> {
            if (StringUtils.hasText(s)) {
                return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").parse(s, LocalDateTime::from);
            }
            return null;
        });
        registry.addConverter(String.class, LocalTime.class, s -> {
            if (StringUtils.hasText(s)) {
                return LocalTime.parse(s);
            }
            return null;
        });
        registry.addConverter(String.class, YearMonth.class, s -> {
            if (StringUtils.hasText(s)) {
                return YearMonth.parse(s);
            }
            return null;
        });
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(fastJsonHttpMessageConverter());
    }

    /**
     * 消息转换器
     */
    @Bean
    public HttpMessageConverter<Object> fastJsonHttpMessageConverter() {
        //创建convert消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        // fastJson配置信息,是否需要格式化JSON
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        //获取json格式化需要格式
        fastJsonConfig.setSerializeFilters((ValueFilter) (o, s, source) -> {
            if (source instanceof LocalDateTime) {
                return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format((LocalDateTime) source);
            }
            return source;
        });
//        SerializerFeature.BrowserCompatible,
//                SerializerFeature.WriteNullStringAsEmpty
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullListAsEmpty
        );
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        // 在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return fastConverter;
    }
}
